#include<iostream>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}
int main(int argc,char*argv[])
{
    //1.创建套接字
    // 1.客户端从网络中获取数据，得创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socker error" << std::endl;
        return 1;
    }
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    
    std::string ip=argv[1];
    std::uint16_t port=std::stoi(argv[2]);
    //主机信息 :通过参数列表来获取
    //还得转换为网络字节序列
    struct sockaddr_in server;
    server.sin_family=AF_INET;
    server.sin_port=htons(port);
    server.sin_addr.s_addr=inet_addr(ip.c_str());  //四点ip转化为4字节ip
    socklen_t len=sizeof(server);
    

    //2.绑定，我们自己不要手动绑定，一般由OS自由随机选择！
    //3.connect连接服务器
    int n=connect(sockfd,(const struct sockaddr*)&server,len);
    if(n<0)
    {
        cerr << "connect error..." << endl; 
        exit(-3);
    }
    
    char buffer[1024];
    std::string message;

    while(1)
    {
        message.clear();
        getline(std::cin,message);
        int n=write(sockfd,message.c_str(),message.size());
        //cout<<message<<endl;
        if(n<0)
        {
            cerr << "write error..." << endl; 
        }
       
        //读取
        int n1=read(sockfd,buffer,sizeof(buffer));
        
        if(n1>0)
        {
            cout<<buffer<<endl;
            memset(buffer,0,sizeof(buffer));
        }
    }

    close(sockfd);
    return 0;
}